package com.banyuan.servlet;

import com.alibaba.fastjson.JSON;
import com.banyuan.domain.ReturnJson;
import com.banyuan.util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;

/**
 * @author 陶继发
 * @version 1.8
 */
@SuppressWarnings("all")
@WebServlet("/translate1")
public class Translate1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String fanti = req.getParameter("fanti");
        System.out.println(fanti);
        Connection connection = null;
        ResultSet re = null;
        StringBuffer sb = new StringBuffer();
        String sql="select * from translate where fanti=?";
        try {
             connection = JDBCUtil.getConnection();
            for (int i = 0; i < fanti.length(); i++) {
                String s = String.valueOf(fanti.charAt(i));
                 re = JDBCUtil.executeQuery(connection, sql, s);
                 if(re.next()){
                     String jianti = re.getString("jianti");
                     sb.append(jianti);
                 }else {
                     sb.append(s);
                 }
            }
            ReturnJson returnJson = new ReturnJson();
            returnJson.setJian(sb.toString());
            String jianJson = JSON.toJSONString(returnJson);
            resp.getWriter().print(jianJson);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                Statement statement = re.getStatement();
                JDBCUtil.close(statement);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            JDBCUtil.close(re);
            JDBCUtil.close(connection);
        }
    }
}
